/**
 * Created by asus on 2017/4/14.
 */
//# sourceURL=register/vm/patientList.js

require(["jquery", "bbcare", "bootstrap", "jquery.dataTables", 'bootstrap.dataTables'], function ($, $bb, bs, $jTable, $bTable) {
    var URL = $bb.baseUrl("department") + "followup/service"
    var sessionId = sessionStorage.sessionId
    //添加宣教
    var addMission = function () {
        $bb.openPage("addMissionTemplate")
    }
    var topbars = [
        {
            "icon": "fa fa-plus",
            "name": "添加宣教",
            "callback": addMission
        }
    ]
    $bb.toolbar(topbars)
    var oTable = $("#myEduTable").DataTable({
        pageLength: 15,             //默认条数
        lengthMenu: [15, 30, 60],//每页显示记录数options选项
        info: true,          //是否使用表格左下角的信息；
        destroy: true,
        stateSave: false,
        ordering: false,     //是否允许Datatables开启排序
        paging: true,        //默认true ,开启分页
        searching: true,    //默认true,是否开启搜索
        serverSide: true,   //是否启用服务器端处理模式，false,在客户端处理，true在服务器端处理；
        ajax: {
            url: URL + "/education/listForDatatableQuery?sessionId=" + sessionId,
            type: "post",
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            data: function (args) {
                var data = JSON.stringify({
                    data: {
                        "args": JSON.stringify(args),
                        "sortField": 2,     //1:按时间排序 2 按浏览量 3 置顶
                        "title": $("#myEduTable_filter>label>input[type='search']").val()  //模糊查询条件
                    }
                })
                return data
            },
            dataSrc: function (data) {
                if (data.rows.length < 15) {
                    var eTime = 15 - data.rows.length
                    for (var i = 0; i < eTime; i++) {
                        data.rows.push({})
                    }
                }
                return data.rows
            }
        },
        columns: [
            {
                data: 'pushTypeName',
                defaultContent: ""
            },          //推送类型
            {
                data: 'title',
                defaultContent: ""
            },          //宣教标题
            {
                data: 'browseCount',
                defaultContent: ""
            },    //浏览量
            {
                data: function (row, type, set, meta) {
                    //1,宣教中，2，暂停宣教宣;
                    if (row.status == 1) {
                        var status = "宣教中"
                    } else if (row.status == 2) {
                        status = "已暂停"
                    }
                    return status
                },
                defaultContent: ""
            },
            {
                data: function (row, type, set, meta) {  //按钮组：
                    if (!$.isEmptyObject(row)) {
                        if (row.status == "1") {
                            var html = "暂停"
                        } else if (row.status == "2") {
                            html = "启用"
                        }
                        let role = JSON.parse($bb.getSessionStorage("account")).role
                        if (role.indexOf('ReadOnly') == -1) {
                            var editBtn = '<a class="edit">编辑</a>'
                            var deleteBtn = '<a class="delete">删除</a>'
                            var enable = '<a class="enable">' + html + '</a>'
                        } else {
                            editBtn = ''
                            deleteBtn = ''
                            enable = ''
                        }
                        return '<a class="preview">预览</a>&nbsp;' +
                            editBtn +
                            '&nbsp;' +
                            enable +
                            '&nbsp;' +
                            deleteBtn +
                            '&nbsp;'
                    }
                },
                defaultContent: ""
            }
        ],
        rowCallback: function (row, data, index) {
            var id = data.id //获取当前行的宣教id;
            var status = data.status //获取当前行的宣教状态;
            $('td:eq(4) a', row).click(function () {
                var attr = $(this).attr("class")
                if (attr == "delete") {
                    if (confirm("您确定删除该条宣教内容么？")) {
                        oTable.bStateSave = true
                        deleteId(id)
                    }
                } else if (attr == "enable") {
                    var self = this
                    changeStatus(self, status, id)
                } else if (attr == "preview") {
                    $("#tpl").html(data.content)
                    $("#myModal").modal("show")
                    $(".refresh").click(function () {
                        $("#tpl").empty().html(data.content)
                    })
                } else if (attr == "edit") {
                    var obj = { "missionId": id }
                    $bb.openPage("editMission", obj)
                }
            })
        }
    })
    //更改宣教状态：
    function changeStatus (self, status, id) {
        var text = $(self).text()
        if (text == "启用" && status == "2") {
            var opCode = 1
            changeAjax(id, opCode)
        } else if (text == "暂停" && status == "1") {
            opCode = 2
            changeAjax(id, opCode)
        }
    }
    function changeAjax (id, opCode) {
        $bb.ajax({
            url: URL + "/education/stopAndEnable",
            type: "post",
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            data: JSON.stringify({
                data: {
                    "contentId": id,
                    "opCode": opCode
                }
            }),
            success: function (data) {
                if (data.success) {
                    oTable.ajax.reload(null, false)
                }
            },
            error: function (data) { }
        })
    }
    //删除：
    function deleteId (id) {
        $bb.ajax({
            url: URL + "/education/remove",
            type: "post",
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            data: JSON.stringify({
                data: {
                    "contentIds": [id]
                }
            }),
            success: function (data) {
                if (data.success) {
                    var start = $("#myEduTable").dataTable().fnSettings()._iDisplayStart
                    var total = $("#myEduTable").dataTable().fnSettings().fnRecordsDisplay()
                    if (total - start == 1) {
                        if (start > 0) {
                            $("#myEduTable").dataTable().fnPageChange('previous', true)
                            alert("删除成功！")
                        }
                    }
                    oTable.ajax.reload(null, false)
                    $("#myEduTable").dataTable().bStateSave = false
                }
            },
            error: function (data) { }
        })
    }

    //周排行：
    var today = new Date()
    var y = today.getFullYear(), m = today.getMonth() + 1, d = today.getDate()
    var h = today.getHours(), ms = today.getMinutes(), s = today.getSeconds()
    var hms = (h > 10 ? h : "0" + h) + ":" + (ms > 10 ? ms : "0" + ms) + ":" + (s > 10 ? s : "0" + s)

    var startTime = getBeforeDate(7) + " " + hms             //7天前
    var endTime = y + "-" + (m > 10 ? m : "0" + m) + "-" + (d > 10 ? d : "0" + d) + " " + hms
    $bb.ajax({
        url: URL + "/education/list",
        type: "post",
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        data: JSON.stringify({
            data: {
                "endTime": endTime,
                "startTime": startTime,
                "rows": 7, //展示个数
                "sortField": 2  //最近一周宣教的按浏览量排序
            }
        }),
        success: function (data) {
            if (data.success) {

                tpl(data.rows, "#weekList")
            }
        },
        error: function (data) { }
    })
    //总排行：
    $bb.ajax({
        url: URL + "/education/list",
        type: "post",
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        data: JSON.stringify({
            data: {
                "rows": 7, //展示个数
                "sortField": 2  //总量按照浏览量排序：
            }
        }),
        success: function (data) {
            if (data.success) {
                tpl(data.rows, "#allList")
            }
        },
        error: function (data) { }
    })
    //页面模板；
    function tpl (value, dom) {
        var lis = ""
        for (var i = 0; i < value.length; i++) {
            lis += '<li>' + (i + 1) + '、' + value[i].title + ' <span class="pull-right"><i class="fa fa-eye" aria-hidden="true"></i>' + value[i].browseCount + '</span></li>'
        }
        $(dom).empty().append(lis)
    }

    function getBeforeDate (n) {
        var n = n
        var d = new Date()
        var year = d.getFullYear()
        var mon = d.getMonth() + 1
        var day = d.getDate()
        if (day <= n) {
            if (mon > 1) {
                mon = mon - 1
            }
            else {
                year = year - 1
                mon = 12
            }
        }
        d.setDate(d.getDate() - n)
        year = d.getFullYear()
        mon = d.getMonth() + 1
        day = d.getDate()
        s = year + "-" + (mon < 10 ? ('0' + mon) : mon) + "-" + (day < 10 ? ('0' + day) : day)
        return s
    }
});

